package com.bango.paymentsdk.sdk;

import android.app.AlertDialog;
import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;

/**
 * Wrapper around the Bango Payment Flows
 */
public class Bango {

    private Context Context;

    /**
     * Creates an object to start a Bango Payment Flow.
     *
     * @param context
     */
    public Bango(Context context){
        Context = context;
    }

    /**
     * Starts a Bango Payment Flow using a Bango number.
     *
     * @param bango Bango number created from the Management Tools website representing the content.
     * @param callback Callback that will be called when the user finishes the Bango Flow
     */
    public void startPaymentWithBangoNumber(String bango, PaymentResultCallback callback){
        this.startPayment(String.format(Constants.BangoEntry,bango), callback);
    }

    /**
     * Starts a Bango Payment Flow using a Billing Configuration ID.
     *
     * @param bcid ID created using the Bango WebServices
     * @param callback Callback that will be called when the user finishes the Bango Flow
     */
    public void startPaymentWithBillingConfiguration(String bcid, PaymentResultCallback callback){
        this.startPayment(String.format(Constants.BangoEntry,bcid), callback);
    }

    private void startPayment(String url, final PaymentResultCallback callback){
        AlertDialog.Builder builder = new AlertDialog.Builder(Context);
        LayoutInflater inflater = LayoutInflater.from(Context);

        View v = inflater.inflate(R.layout.web_dialog, null);

        EditText edit = (EditText) v.findViewById(R.id.bango_hidden_edit);
        edit.setFocusable(true);
        edit.requestFocus();

        builder.setView(v);

        final AlertDialog dialog = builder.create();
        dialog.show();

        WebView web = (WebView) v.findViewById(R.id.bango_web_view);
        web.getSettings().setJavaScriptEnabled(true);
        web.loadUrl(url);

        web.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String urlStr) {
                Uri url = Uri.parse(urlStr);
                if (url.getQueryParameter("ResponseCode") != null) {
                    long transactionId= 0;
                    if(url.getQueryParameter("BangoTransactionId") != null)
                        transactionId = Long.parseLong(url.getQueryParameter("BangoTransactionId"));
                    callback.onResult(url.getQueryParameter("ResponseCode"), transactionId);
                    dialog.dismiss();
                } else {
                    view.loadUrl(urlStr);
                }
                return false;
            }
        });
    }
}
